<template>
  <div class="p-[16px]" @scroll="handleScroll" ref="commentListRef">
    <!-- 只在有评论时显示评论数量 -->
    <div v-if="comments.length" class="text-[14px] ml-[8px] mb-[12px] text-gray-500">
      共 {{ total }} 条评论
    </div>
    
    <!-- 评论列表 -->
    <div>
      <CommentItem 
        v-for="comment in comments" 
        :key="comment.id" 
        :comment="comment"
        @reply="$emit('reply', $event)"
      />
    </div>

    <!-- 空评论状态 -->
    <div v-if="!comments.length" class="flex flex-col items-center py-[20px] gap-[20px]">
      <img 
        src="http://127.0.0.1:9000/xiaohashu/blank.png" 
        class="w-[100px] h-[100px]"
      />
      <div class="flex items-center justify-center text-[14px]">
        <div class="text-gray-500">这是一片荒地</div>
        <div 
          class="text-[#13386c] ml-[4px] cursor-pointer"
          @click="onClickComment"
        >
          点击评论
        </div>
      </div>
    </div>

    <!-- 到底了提示 -->
    <div v-if="comments.length" class="flex flex-col items-center end-container">
        - THE END - 
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import CommentItem from './CommentItem.vue'

const props = defineProps({
  comments: {
    type: Array,
    default: () => []
  },
  total: {
    type: [Number, String],
    default: '0'
  },
  hasMore: {
    type: Boolean,
    default: false
  },
  moreCount: {
    type: Number,
    default: 0
  }
})

const emit = defineEmits(['load-more', 'click-comment', 'reply'])
const commentListRef = ref(null)

// 处理滚动事件
const handleScroll = (e) => {
  if (!props.comments.length || !props.hasMore) return

  const container = e.target
  const scrollTop = container.scrollTop
  const scrollHeight = container.scrollHeight
  const clientHeight = container.clientHeight

  // 当滚动到距离底部 50px 时触发加载
  if (scrollHeight - scrollTop - clientHeight < 50) {
    console.log('已经滚动到最后一条评论，准备加载下一页数据...')
    emit('load-more')
  }
}

// 组件挂载时添加滚动监听
onMounted(() => {
  if (commentListRef.value) {
    commentListRef.value.addEventListener('scroll', handleScroll)
  }
})

// 组件卸载时移除滚动监听
onBeforeUnmount(() => {
  if (commentListRef.value) {
    commentListRef.value.removeEventListener('scroll', handleScroll)
  }
})

// 点击评论处理
const onClickComment = () => {
  emit('click-comment')
}
</script> 

<style scoped>
.end-container {
  margin-top: 24px;
  margin-bottom: 24px;
  font-size: 12px;
  line-height: 16px;
  color: rgba(51, 51, 51, 0.6);
}

</style>